import Taro, { useRouter } from "@tarojs/taro";
import { PageContainer, View } from "@tarojs/components";
import { useBoolean, useCreation } from "ahooks";

import ByRow from "@/components/ui/ByRow";
import ByTag from "@/components/ui/ByTag";
import Money from "@/components/app/Money";
import Card from "@/components/common/Card";
import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import Moment from "@/components/app/Moment";
import ByButton from "@/components/ui/ByButton";
import ByImageGroup from "@/components/ui/ByImageGroup";
import CustomerCard from "@/components/app/CustomerCard";
import TagRadioGroup from "@/components/app/TagRadioGroup";
import PopupContainer from "@/components/app/PopupContainer";
import ApprovalaProcess from "@/components/app/ApprovalaProcess";

import ApiWork from "@/api/work";
import ApiFinance from "@/api/finance";
import ApiWorkflow from "@/api/workflow";
import useEnum from "@/hooks/useEnum";
import useFetch from "@/hooks/useFetch";
import useForm from "@/hooks/useForm";
import useApproval from "@/hooks/useApproval";

import { TaskDetail } from "@/types/global";
import ByText from "@/components/ui/ByText";
import ByCellGroup from "@/components/ui/ByCellGroup";
import dayjs from "dayjs";

type AfterSaleDetail = {
  feeCategory: string;
  businessId: number;
  createUserName: string;
  createTime: number;

  decorationAddress: string;
  customerName: string;

  applyAmount: number;
  summary: string;
  remark: string;

  status: -1 | 0 | 1 | 2;

  tagetUserName: string;
  rejectDate: number;
  rejectReason: string;
  rejectUserName: string;
  /**
   * 质保期
   */
  planWarrantyDate: string;

  fileRefererId: string[];
  repairBill: {
    billNo: string;
    headerName: string;
    repairContent: string;
    contractAmount: number;
  };
};

// 更新售后类型
const PopupUpdateFeeCategory = ({
  source,
  onCancel,
  onSuccess,
}: {
  source: AfterSaleDetail;
  onSuccess: () => void;
  onCancel: () => void;
}) => {
  // 售后类型Options 选项
  const { options } = useEnum({ className: "公司类型" });

  const { fileRefererId } = source;
  const { loading, model, setModel, submit } = useForm(
    ApiFinance.afterSaleCreate,
    {
      showLoading: true,
      method: "PUT",
      defaultModel: {
        ...source,
        fileRefererId: fileRefererId || [],
      },
      onSuccess() {
        Taro.showToast({ title: "更新成功！" });
        onSuccess();
      },
    }
  );

  return (
    <PopupContainer title="更改售后类型" onCancel={onCancel}>
      <View className="px-3">
        <ByCell label="售后类型" vertical requierd>
          <TagRadioGroup
            value={[model.feeCategory]}
            options={options}
            labelKey="label"
            valueKey="label"
            onChange={([e]) => setModel({ feeCategory: e })}
          />
        </ByCell>

        <ByButton
          size="large"
          loading={loading}
          className="w-2/3 mt-10 mb-3"
          onClick={() => submit()}
        >
          提交
        </ByButton>
      </View>
    </PopupContainer>
  );
};

export default () => {
  const { params } = useRouter();
  const wl_id = Number(params.wl_id);
  const paymentBillId = Number(params.businessId);
  const intentCustomerId = Number(params.intentCustomerId);

  // 售后详情
  const { data, refresh } = useFetch<AfterSaleDetail>(
    ApiFinance.afterSaleDetail,
    { defaultParams: [{ paymentBillId }] }
  );

  // 签订合同详情
  const { data: contractInfo } = useFetch(ApiWork.getContractInfo, {
    defaultParams: [{ intentCustomerId }],
    onAfter: (res: any) => res.contractInfo,
  });

  console.log("contractInfo", contractInfo);

  // 审核弹窗类型: "modify" | "rejected"
  const [visibleModify, { setTrue, setFalse }] = useBoolean();

  // 获取审批流详情
  const { data: workflowDetail, refresh: refreshWlDetail } =
    useFetch<TaskDetail>(ApiWorkflow.detail, {
      defaultParams: [{ workflowInstanceId: wl_id }],
    });

  // 拿到 当前激活审批流节点
  // const [approverNode, setApproverNode] = useState<TaskStep>();

  // 审批操作
  const {
    visible,
    approverNode,
    setApproveNode,
    PopupApproval,
    onApproved,
    onRejected,
    onCancal,
  } = useApproval(refreshWlDetail);

  const closePopup = () => (setFalse(), onCancal());

  // 是否在质保期内
  const isValid = useCreation(() => {
    const { planWarrantyDate: date } = data || {};
    if (!date) return false;
    return dayjs().isSameOrBefore(date);
  }, [data]);

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          !!approverNode && (
            <ByRow>
              <ByButton
                className="w-2/5"
                type="error"
                variant="filled"
                size="large"
                onClick={onRejected}
              >
                驳回
              </ByButton>
              <ByButton
                size="large"
                className="w-3/5 ml-3"
                onClick={onApproved}
              >
                通过
              </ByButton>
            </ByRow>
          )
        }
      >
        <CustomerCard source={data} address={data?.decorationAddress} />

        <Card className="m-3">
          <ByCell label="施工工期：" size="small">
            <Moment value={contractInfo?.realBeginDate} />
            ~
            <Moment value={contractInfo?.realEndDate} />
          </ByCell>

          <ByCell label="质保期：" size="small">
            <Moment className="mr-2" value={data?.planWarrantyDate} /> 截至
            <ByText type={isValid ? "primary" : "error"}>
              {isValid ? "质保中" : "质保结束"}
            </ByText>
          </ByCell>
        </Card>

        <ByCellGroup title="售后维修单" className="m-3">
          <View className="py-3">
            {data?.repairBill ? (
              <>
                <ByText block>{data?.repairBill?.billNo}</ByText>
                <ByText size="sm" block className="mt-2" type="third">
                  报修内容：{data?.repairBill?.repairContent}
                </ByText>
                <ByRow className="mt-1" content="between">
                  <ByText size="sm" type="third">
                    维修负责人：{data?.repairBill?.headerName}
                  </ByText>
                  <ByText size="sm" type="third">
                    合计承包金额：¥{data?.repairBill?.contractAmount}
                  </ByText>
                </ByRow>
              </>
            ) : (
              <ByText block type="third" className="text-center">
                未关联维修单
              </ByText>
            )}
          </View>
        </ByCellGroup>

        <Card className="m-3">
          <ByCell label="售后类型:" size="small" labelWidth="5em">
            <ByTag type="warning" size="small">
              {data?.feeCategory}
            </ByTag>

            {approverNode?.isCanEdit && (
              <ByButton size="small" className="mr-0" onClick={setTrue}>
                更改
              </ByButton>
            )}
          </ByCell>

          <ByCell label="维修负责人:" size="small" labelWidth="5em">
            {data?.tagetUserName}
          </ByCell>
          <ByCell label="申请金额:" size="small" labelWidth="5em">
            <Money value={data?.applyAmount} />
          </ByCell>
          <ByCell label="保修内容:" size="small" labelWidth="5em">
            {data?.summary || "-"}
          </ByCell>
          <ByCell label="备注:" size="small" labelWidth="5em">
            {data?.remark || "-"}
          </ByCell>
          <ByCell label="附件:" size="small" labelWidth="5em" vertical>
            <ByImageGroup urls={data?.fileRefererId} />
          </ByCell>
        </Card>

        <Card className="m-3">
          {workflowDetail && (
            <ApprovalaProcess
              showTitle
              source={workflowDetail}
              onChangeStatus={setApproveNode}
            />
          )}
        </Card>
      </Page>

      <PageContainer
        round
        show={visibleModify || visible}
        onAfterLeave={closePopup}
      >
        {visible ? (
          <PopupApproval />
        ) : visibleModify ? (
          <PopupUpdateFeeCategory
            source={data!}
            onCancel={closePopup}
            onSuccess={() => (closePopup(), refresh())}
          />
        ) : null}
      </PageContainer>
    </>
  );
};
